using System.Collections.Generic;
using System.Threading.Tasks;
using EmotionChat.Services;
using Mvvm.Helpers;
using Mvvm.Models;
using SQLite;

namespace Mvvm.Services;

public class ChatDataProcessedStorage : IChatDataProcessedStorage
{
    private const string DbName = "chatprocesseddatadb.sqlite3";
    public static readonly string ChatDataDbPath =
        PathHelper.GetLocalFilePath(DbName);

    private SQLiteAsyncConnection _connection;
    private SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(ChatDataDbPath);
        
    public async Task InitializeAsync()
    {
        await Connection.CreateTableAsync<ChatProcessedData>();
    }

    public async Task InsertAsync(ChatProcessedData chatProcessedData, int identifier)
    {
        // 如果没有这个表，则调用初始化
        await InitializeAsync();
        // 如果该标识符已存在，则不插入
        if (await Connection.Table<ChatProcessedData>().Where(c => c.Identifier == identifier).CountAsync() > 0)
        {
            return;
        }
        chatProcessedData.Identifier = identifier;
        
        await Connection.InsertAsync(chatProcessedData);
    }

    public async Task<IList<ChatProcessedData>> ListAsync()
    {
        // 如果没有这个表，则调用初始化
        await InitializeAsync();
        return await Connection.Table<ChatProcessedData>().ToListAsync();
    }

    //根据标识符查询
    public async Task<List<ChatProcessedData>> QueryAsync(int identifier) =>
        await Connection.Table<ChatProcessedData>()
            .Where(c => c.Identifier == identifier)
            .ToListAsync();
    
    //根据用户名查询
    public async Task<List<ChatProcessedData>> QueryAsync(string user1,string user2) =>
        await Connection.Table<ChatProcessedData>()
            .Where(c => c.Username1 == user1 && c.Username2 == user2)
            .ToListAsync();

    public async Task DeleteAsync()
    {
        await Connection.DeleteAllAsync<ChatProcessedData>();
    }
}